package lrscp.lib;

import java.util.concurrent.LinkedBlockingQueue;

public class Handler {
    private static LinkedBlockingQueue<Runnable> runQueue = new LinkedBlockingQueue<Runnable>();
    static boolean exit = false;
    private static Thread handlerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!exit) {
                try {
                    Runnable run = runQueue.take();
                    if (run != null) {
                        run.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    static {
        handlerThread.start();
    }

    public static void post(Runnable runnable) {
        runQueue.offer(runnable);
    }

    public static void remove(Runnable runnable) {
        while (runQueue.contains(runnable)) {
            runQueue.remove(runnable);
        }
    }
    
    public static void dispose(){
        exit = true;
        runQueue.offer(new Runnable() {
            @Override
            public void run() {
            }
        });
        try {
            handlerThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
